package cn.yunhe.controller;

import cn.yunhe.entity.News;
import cn.yunhe.entity.User;
import cn.yunhe.service.impl.NewsServiceImpl;
import com.github.pagehelper.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class NewsController {
    @Resource
    private NewsServiceImpl newsService;

    @RequiresPermissions("/view/news-list.html")
    @RequestMapping("/toSystem.do")
    public void toSystem(HttpServletResponse response) throws IOException {
        response.sendRedirect("/view/news-list.html");
    }

    @RequestMapping("newsPage")
    public Map queryNewsByPage(int pageSize, int pageNum, News news){
        Map map = new HashMap();
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        map.put("news", news);
        Page page = newsService.getNewsListByPage(map);
        map.put("page", page);
        map.put("totalPage", page.getPages());

        return map;
    }

    @RequestMapping("/addNews")
    public int addNews(News news , HttpSession session) {
         User user= (User) session.getAttribute("Curr_User");
         news.setUser(user);
        return newsService.addNews(news);
    }

    @RequestMapping("/delNews")
    public int delNews(News news) {
        System.out.println("id " +news.getNewsId());
        return newsService.delNews(news);
    }

    @RequestMapping("/getNewsById")
    public ModelAndView getNewsById(News news, HttpServletRequest request) {
        News n = newsService.getNewsById(news);
        request.setAttribute("data", n);
        return new ModelAndView("updNews");
    }

    @RequestMapping("/updNews")
    public int updNews(News news ) {
        return newsService.updNews(news);
    }


    public NewsServiceImpl getNewsService() {
        return newsService;
    }

    public void setNewsService(NewsServiceImpl newsService) {
        this.newsService = newsService;
    }
}
